<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<link rel="stylesheet" href="${baseURL}/themes/default/css/filter.css" />
<link rel="stylesheet" href="${baseURL}/js/mCustomScrollbar/jquery.mCustomScrollbar.css" />
<script src="${baseURL}/js/mCustomScrollbar/jquery.mCustomScrollbar.concat.min.js"></script>
<script src="${baseURL}/js/handlebars/handlebars-min.js"></script>
	<div class="filter-bar">
		<!-- 过滤器 -->
		<div id="my-filter">我的筛选：<span id="currentFilter"></span></div>
		
		<!-- 保存 -->
		<div class="top-filter">
			<div class="save-filter-btn"><a>保存过滤器</a></div>
		</div>
		
		<!-- 更多 -->
		<div class="more-filter">
			<div class="more-condition">
				更多筛选条件 <i class="fa fa-caret-down"></i> <i class="fa fa-caret-up"></i>
				<div class="more">
					<div id="filter_list_more">
						<ul class="more-filter-content"></ul>
					</div>
					<div class="my-filter"><i class="fa fa-filter"></i><span>过滤器管理</span></div>
				</div>
			</div>
		</div>
	</div>
	
	<!-- 保存过滤器 -->
	<form id="save_filter_form" style="display: none;">
		<input id="filter_name_input" type="text" name="filterName" maxlength="28" placeholder="请输入过滤器名称" />
	</form>
	
	<div id="saveFilterBtnClick" is-click="true" style="display: none;"></div>
	
	<div id="save-update" style="display: none;">
		<div style="position: relative;">
			<i style="font-size: 50px;position: absolute;top: 10px;left: 10px;color: #66ccff;" class="fa fa-exclamation-circle" aria-hidden="true"></i>
			<span style="position: absolute;left: 69px;top: 14px;font-size: 16px;color: #8B8878;">亲，您是否要更新过滤器或者另外再创建一个过滤器</span>
		</div>
	</div>
	<script id="system-filter" type="text/x-handlebars-template">
		<div id="{{id}}" class="filter" state="{{state}}"><a title="{{name}}">{{name}}</a></div>
	</script>
	<script id="user-filter" type="text/x-handlebars-template">
		<div id="{{id}}" class="filter" state="{{state}}"><a title="{{name}}">{{name}}</a><i title="删除过滤器【{{name}}】" class="fa fa-times-circle"></i><i title="分享过滤器【{{name}}】" class="fa fa-share"></i></div>
	</script>
	<script type="text/javascript">
		var saveFilterBtn = $('.save-filter-btn');
		var topFilter = $('.top-filter');
		var moreFilterContent = $('.more-filter-content');
		var systemFilter = Handlebars.compile($('#system-filter').html());
		var userFilter = Handlebars.compile($('#user-filter').html());
		var filterArr = {};
		
		$(function(){
			$("#filter_list_more").mCustomScrollbar({
	    		axis:"yx",
	    		theme:"minimal-dark",
	    		scrollbarPosition:"outside"
	    	});
			
			// 保存按钮
			$('.save-filter-btn').click(function(){
				saveFilter();
			});
			
			// 过滤器
			$('.filter-bar').on('click', '.filter>a', function(){
				var filterDiv = $(this).parent();
				var id = filterDiv.attr('id');
				
				var currentFilter = $(".current-filter");
				if (currentFilter != null) {
					currentFilter.show();
					currentFilter.remove("current-filter");
				}
				setCurrentFilter(id);
				renderSelectorByFilter(filterArr[id].content);
			});
			
			// 删除按钮
			$('.filter-bar').on('click', '.filter .fa-times-circle', function(){
				var filterDiv = $(this).parent();
				var id = filterDiv.attr('id');
				var filterName = $(this).prevAll('a').attr('title');
				deleteFilter(id, filterName);
			});
			
			// 分享按钮
			$('.filter-bar').on('click', '.filter .fa-share', function(){
				shareFilter($(this).parent().attr('id'));
			});

			$('.my-filter').click(function(){
				parent.f_addTab('myFilter', '我的过滤器', '${baseURL}/jdbc/common/basecommonlist/list.do?mdCode=filter&defaultParams={"userId":"currentUserId()"}');		
			});
			
			loadFilter();
		});
		
		/*
		 * 通过过滤器加载数据
		 */
		function renderSelectorByFilter(content){
			selector.resetSelector();
			var condition = eval('(' + content + ')');
			for(c in condition) {
				selector.setSelectorValue(condition[c].name, condition[c].value, null);
			}
			selector.search();
		}
		
		/*
		 * 加载过滤器数据
		 */
		function loadFilter(){
			$.ajax({
				url: '${baseURL}/filter/filter/mdfilterlist/loadFilterJson.do',
				type: 'post',
				data: {"mdCode":'${param.mdCode}',"mdId":"${param.mdId}"},
				dataType: 'json',
				success: function(data){
					if (data && data.Rows) {
						setFilterToPage(data.Rows);
						flushFilterCount(data.Rows);
					}
				}
			});
		}
		
		/*
		 * 刷新过滤器计数
		 */
		function flushFilterCount(){
			$(".top-filter>.filter").each(function(){
				var e = filterArr[$(this).attr("id")];
				$.ajax({
					url: '${baseURL}/jdbc/common/basecommonlist/filterCount.do',
					type: 'post',
					data: {searchParam:e.content,mdId:'${param.mdId}',mdCode:'${param.mdCode}'},
					dataType: 'json',
					success: function(data) {
						if(data && data.count){
							var $filter = $("#"+e.id+">a");
							$filter.text($filter.attr("title")+"("+data.count+")");
						}
					}
				});
			});
		}
		
		/*
		 * 将过滤器设置到页面上
		 */
		function setFilterToPage(rows) {
			saveFilterBtn.prevAll().remove();
			moreFilterContent.children().remove();
			
			var isTop = true;
			$.each(rows, function(i, e){
				isTop = renderFilter(e,isTop);
			});
		}
		
		function renderFilter(e,isTop){
			var template = e.state == 0 ? systemFilter : userFilter;
			var html = template(e);
			if (isTop && isTopFilter(html)) {
				saveFilterBtn.before(html);
			} else {
				var li = $("<li></li>");
				li.append(html);
				moreFilterContent.append(li);
				isTop = false;
			}
			filterArr[e.id] = e;
			return isTop;
		}
		
		/*
		 * 判断过滤器是放在顶部还是放在更多那里
 		 */
		function isTopFilter(html) {
			var isTop = false;
			var filter = typeof html == 'string' ? $(html) : html;
			filter.attr('visibility', 'hidden');
			topFilter.append(filter);
			var moreFilterLeft = $('.more-filter').offset().left;
			var topFilterRight = topFilter.offset().left + topFilter.width();
			if (topFilterRight < moreFilterLeft) {
				isTop = true;
			}
			filter.remove();
			return isTop;
		}
		
		/*
		 * 保存过滤器弹出框
		 */
		function saveFilter(){
			var content = JSON.stringify(selector.getSelectorValue());
			if ($(".current-filter").length > 0) {
 				updateDialog(content);
			} else {
 				createDialog(content);
			}
		}
		
		/*
		 * 输入过滤器名的弹出框
		 */
		function createDialog(content) {
			$('#save_filter_form').find("input").val("");
 			$.ligerDialog.open({
				title: '保存过滤器',
				target: $('#save_filter_form'),
				height: 105,
				width: 320,
				isShade: true,
				buttons: [
				  
					{text: "保存", className: 'fa fa-check',
						onclick: function (item, dialog) {
							var name = $('#filter_name_input').val();
							if(!name || name == '') {
								win.$.ligerDialog.warn('请输入过滤器名');
								return;
							}
							if (name.length > 28) {
								win.$.ligerDialog.warn('过滤器长度不能超过28个字符');
								return;
							}
							var params = new Object();
							params.name = name;
							params.content = content;
							params.mdCode = '${param.mdCode}';
							params.mdId = '${param.mdId}';
							params.pageUri = getPageUri();
							saveFileter(params, dialog);
						} 
			    	},
			    	{ text: '取消', className: 'fa fa-close',
						onclick: function (item, dialog) { dialog.hide(); } 
					}
				]
			});
			$("#filter_name_input").focus();
		}
		
		/*
		 * 更新过滤器的弹出框
		 */
		function updateDialog(content){
			$.ligerDialog.open({
				title: '过滤器',
				target: $('#save-update'),
				height: 150,
				width: 320,
				isShade: true,
				buttons: [
				   { text: '取消', className:"red_btn fa fa-reply fa-btn",
						onclick: function (item, dialog) { dialog.close(); } 
					},
					{text: "另存", className:"blue-btn fa fa-save fa-btn",
						onclick: function (item, dialog) {
							dialog.close();
							createDialog(content);
						} 
			    	},
			    	{text: "更新", className:"green-btn fa fa-save fa-btn",
						onclick: function (item, dialog) {
							if ($(".current-filter").attr('state') == 0) {
								win.$.ligerDialog.warn('亲，不能更新固定过滤器哦！');
								return false;
							}
							saveFileter({id:$(".current-filter").attr("id"), content:content}, dialog);
						} 
			    	}
				]
			});
		}
		
		/*
		 * 保存过滤器
		 */
		 var isSave = true;
		function saveFileter(params, dialog){
			// 防止重复提交
			if(isSave){
				isSave = false;
				$.ajax({
					url: '${baseURL}/filter/filter/mdfiltersave/saveFilter.do',
					type: 'post',
					data: params,
					dataType: 'json',
					success: function(data){
						if(data.hasOk) {
							renderFilter(data.bean,true);
							dialog.hide();
							win.$.ligerDialog.success(data.message);
						} else {
							win.$.ligerDialog.error(data.message);
						}
					},
		            complete:function(){
						isSave = true;
					}
				});
			}
		}
		
	    /*
	     * 删除过滤器
	     */
		function deleteFilter(id, name){
			if(!id || id == '') {
				return false;
			}
			var currentFilter = $(".current-filter");
	    	if (currentFilter != null && currentFilter.attr('id') == id) {
	    		win.$.ligerDialog.warn('亲，正在使用的过滤器不能删除哦');
	    		return false;
	    	}
	    	
			$.ligerDialog.confirm('亲，确认要删除过滤器【' + name + '】吗?', '删除确认', function(confirm){
				if (confirm) {
					$.ajax({
		    			url: '${baseURL}/filter/filter/mdfilterdelete/delete.do',
		    			type: 'post',
		    			dataType : "json",
						data: "ids="+ id,
						success: function(msg){
							if(msg && msg.hasOk){
								if ($('#' + id).parent("li").length>0) {
									$('#' + id).parent("li").remove();
								} else {
									$('#' + id).remove();
									var mfilter = $(".more-filter-content .filter:first");
									if(mfilter){
										renderFilter(filterArr[mfilter.attr('id')],true);
										$(".more-filter-content>li:first").remove();
									}
								}
								win.$.ligerDialog.success('已删除过滤器【' + name + '】');
							}else{
								win.$.ligerDialog.error("操作失败!失败信息如下:\n"+msg.message+"\n如您对以上信息有疑问，请联系管理人员!");
							}
						}
		    		});
				}
			});
		}
	    
		/*
		 * 分享过滤器
		 */
		function shareFilter(id){
			parent.$.ligerDialog.open({
	  			title:"分享过滤器",
	  			url: "${baseURL}/filter/filter/mdfilteredit/shareFilter.do?mdCode=${param.mdCode}&mdId=${param.mdId}&id=" + id,
				height: 500,
				width: 590,
				isShade:true,
				buttons: [ 
					{ text: '取消', className:"red_btn fa fa-reply fa-btn",
						onclick: function (item, dialog) { dialog.close(); } 
					},
					{text: "分享", className:"green-btn fa fa-save fa-btn",
						onclick: function (item, dialog) {
							dialog.frame.share(function(){
								dialog.close();
							});
						} 
				    }
				] 
			});
		}
		
		function setCurrentFilter(filterId) {
			var currentFilter = null;
			if(filterId){
				currentFilter = $("#"+filterId);
			}else{
				currentFilter = $(".top-filter>.filter:first");
			}
			if(currentFilter.length>0){
				var a = currentFilter.children('a');
				if (currentFilter.parent().hasClass('top-filter')) {
					currentFilter.addClass('current-filter');
					$('#currentFilter').html('');
					$('#currentFilter').removeAttr('title');
					$('#currentFilter').removeClass('show-current-filter');
				} else {
					currentFilter.hide();
					currentFilter.addClass('current-filter');
					$('#currentFilter').html(a.html());
					$('#currentFilter').attr('title', '当前使用的过滤器：' + a.attr('title'));
					$('#currentFilter').addClass('show-current-filter');
				}
			}
		}
		
		/*
		 * 获取当前页面uri
		 */
		function getPageUri() {
			var uri = window.location.pathname;
			var re = new RegExp('^' + baseURL);
			return uri.replace(re, '');
		}
		
		/*
		 * 屏幕宽度改变时，处理过滤器的显示位置 
 		 */
		window.onresize = function() {
			if ($(window).width() < 350) {
				$('#my-filter').hide();
			} else {
				$('#my-filter').show();
			}
			var moreFilterLeft = $('.more-filter').offset().left;
			var topFilterRight = topFilter.offset().left + topFilter.width();
			if (topFilterRight > moreFilterLeft) {
				while (topFilterRight > moreFilterLeft) {
					var filter = saveFilterBtn.prev();
					if (filter.length == 0) {
						break;
					}
					if (filter.hasClass('current-filter')) {
						$('#currentFilter').html(filter.children('a').html());
						$('#currentFilter').attr('title', '当前使用的过滤器：' + filter.children('a').attr('title'));
						$('#currentFilter').addClass('show-current-filter');
					}
					var li = $('<li></li>');
					li.append(filter);
					moreFilterContent.prepend(li);
					if (filter.hasClass('current-filter')) {
						filter.hide();
					}
					topFilterRight = topFilter.offset().left + topFilter.width();
				}
			} else if (topFilterRight < moreFilterLeft) {
				while (topFilterRight < moreFilterLeft) {
					var li = moreFilterContent.children(':first');
					if (li.length == 0) {
						break;
					}
					var filter = li.children(':first');
					if (filter.hasClass('current-filter')) {
						filter.show();
					}
					var filterId = filter.attr('id');
					 
					var template = (filterArr[filterId].state == 0 ? systemFilter : userFilter);
					var html = template(filterArr[filterId]);
					if (isTopFilter(html)) {
						if (filter.hasClass('current-filter')) {
							$('#currentFilter').html('');
							$('#currentFilter').removeAttr('title');
							$('#currentFilter').removeClass('show-current-filter');
							html = $(html);
							html.addClass('current-filter');
							currentFilter = html;
						}
						saveFilterBtn.before(html);
						li.remove();
					} else {
						if (filter.hasClass('current-filter')) {
							filter.hide();
						}
						break;
					}
					topFilterRight = topFilter.offset().left + topFilter.width();
				}
			}
		}
	</script>